package com.liupaik.pennmarketplace;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LogIn extends Activity {

	// Declare our Views, so we can access them later
	private EditText etUsername;
	private EditText etPassword;
	private Button btnLogin;
	private TextView lblResult;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.login);

		// Get the EditText and Button References
		etUsername = (EditText)findViewById(R.id.username);
		etPassword = (EditText)findViewById(R.id.password);
		btnLogin = (Button)findViewById(R.id.login_button);
		lblResult = (TextView)findViewById(R.id.result);

		//Set Click Listener
		btnLogin.setOnClickListener(new OnClickListener() {
			public void onClick(final View v) {



				// Check Login
				String username = etUsername.getText().toString();
				String password = encrypt(etPassword.getText().toString());
				//String password = etPassword.getText().toString();

				//Pattern p = Pattern.compile("^w+@w+.upenn.edu$");
				Pattern p = Pattern.compile("[a-zA-Z0-9]@[a-zA-Z0-9]+.upenn.edu$");
				Matcher m = p.matcher(username);

				//FIRST CHECK IF THE EMAIL IS VALID
				if (m.find()){			    	  

					//NEED TO GET RID OF ENCRYPT
					final String[] result = login(username,password);
					//String encryptedp = encrypt(result[1]);
					//result[1] = encryptedp;

					//CHECK IF IT PROPERLY CONNECTED TO THE PHP SCRIPT
					if(result[0].equals("Error in connecting...")){
						lblResult.setText(result[0]);
						Toast.makeText(getBaseContext(),"Error in connecting...",Toast.LENGTH_LONG).show();
					}

					//lblResult.setText(password + "\n" + result[1]);

					//CHECK IF USERNAME AND PASSWORD IS VALID

					else if (result[0].equals("Username does not exist!")){
						lblResult.setText("Username does not exist!");
						new AlertDialog.Builder(LogIn.this)	                			  
						.setMessage("Username does not exist!")  
						.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								etUsername.requestFocus();
								etUsername.selectAll();
							}
						})
						.show();
					}
					else if (password.equals(result[1])){

						/////////////////////////////////////////////////	
						////////////////////////////////////////////////		
						final ProgressDialog pdg = ProgressDialog.show(getDialogContext(), "", "Logging In...", true);
						new Thread(){
							public void run() {
								try {
						/////////////////////////////////////////////////	
						////////////////////////////////////////////////	

									lblResult.setText("Login Successful!");
									//lblResult.setText(password + " " + result[1]);
									//lblResult.setText(result[0]);
									SharedPreferences users = getSharedPreferences("Users", MODE_PRIVATE);  
									SharedPreferences.Editor editor = users.edit();
									editor.putString("CurrentUser", result[0]);
									editor.commit();

									Intent myIntent = new Intent(v.getContext(), BuySell.class);
									startActivityForResult(myIntent, 0);

						///////////////////////////////////////////////
						/////////////////////////////////////////////////
								}
								catch (Exception e){
									Log.e("tag",e.getMessage());
								}
								pdg.dismiss();
							}
						}.start();
						/////////////////////////////////////////////////	
						////////////////////////////////////////////////	

					}
					else{
						lblResult.setText("Incorrect password!");
						new AlertDialog.Builder(LogIn.this)	                			  
						.setMessage("Incorrect password!")  
						.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								etPassword.requestFocus();
								etPassword.selectAll();
							}
						})
						.show();
					}
				}
				else{
					lblResult.setText("Not a valid email!");
					new AlertDialog.Builder(LogIn.this)	                			  
					.setMessage("Not a valid email!")  
					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							etUsername.requestFocus();
							etUsername.selectAll();
						}
					})
					.show();

				}

			}
		});
	}

	public static final String LOGIN = "http://www.upennakpsi.org/lololol/pennmarketplace/login.php"; 

	private String[] login(String name, String password) {

		InputStream is = null;

		String result = "";
		String[] returnString = {"",""};

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("name",name));
		nameValuePairs.add(new BasicNameValuePair("password",password));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(LOGIN);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			returnString[0] = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			//returnString += "\nError in converting...";
			Log.e("log_tag", "Error converting result "+e.toString());
		}

		//IF USERNAME DOESN'T EXIST, JUST RETURN THE STRING
		if(result.equals("Username does not exist!")){
			returnString[0] = result;
			return returnString;
		}


		//OTHERWISE, OBTAIN THE USER ID AND PASSWORD
		//parse json data
		try{
			JSONArray jArray = new JSONArray(result);
			JSONObject json_data = jArray.getJSONObject(0);
			returnString[0] = json_data.getString("U_id");
			returnString[1] = json_data.getString("password");

		}catch(JSONException e){
			Log.e("log_tag", "Error parsing data "+e.toString());
		}

		return returnString;
	}   

	public String encrypt(String password){
		String algorithm = "SHA";

		byte[] plainText = password.getBytes();

		MessageDigest md = null;

		try {		
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			e.printStackTrace();
		}

		md.reset();		
		md.update(plainText);
		byte[] encodedPassword = md.digest();

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				sb.append("0");
			}

			sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}
		return sb.toString();
	}

	private Context getDialogContext() {
		Context context;
		if (getParent() != null) context = getParent();
		else context = this;
		return context;
	}






}